<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="培训项目" prop="trainItem">
        <el-input v-model="queryParams.trainItem" placeholder="请输入培训项目" clearable />
      </el-form-item>
      <el-form-item label="培训部门" prop="deptId">
        <el-tree-select style="width:100%" v-model="queryParams.deptId" :data="deptOptions" @node-click="handleNodeClick($event,'queryParams')"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择培训部门" check-strictly  />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['audit:train:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['audit:train:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column label="序号" align="center" width="65" type="index" />
      <el-table-column label="收费站" align="center" prop="deptName" />
      <el-table-column label="计划时间" align="center" prop="planDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>     
      <el-table-column label="培训项目" align="center" prop="trainItem" />
      <el-table-column label="学习内容" align="center" prop="studyContent" />
      <el-table-column label="培训部门" align="center" prop="trainDeptName" />
      <el-table-column label="培训时间" align="center" prop="trainDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.trainDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="培训对象" align="center" prop="trainOb" />
      <el-table-column label="授课人" align="center" prop="teacher" />

      <el-table-column label="培训方式" align="center" prop="trainMethod"></el-table-column>
      <el-table-column label="考核形式" align="center" prop="checkMethod"></el-table-column>
      <el-table-column label="培训文件" align="center" prop="imgList">
        <template #default="scope">
          <image-preview :src="scope.row.imgList" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <span>{{scope.row.status==0?'待培训':'已完成'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleUpdate(scope.row,1)" v-hasPermi="['audit:train:query']">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['audit:train:edit']">完成上报</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['charge:train:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改培训对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="activityRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="收费站" prop="deptId">
              <el-tree-select style="width:100%" class="inputDeep" v-model="form.deptId" :data="deptOptions" @node-click="handleNodeClick($event,'form')"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择收费站" check-strictly clearable :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="planDate">
              <el-date-picker clearable style="width:100%" v-model="form.planDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择" :disabled="isView">
              </el-date-picker>
            </el-form-item>
          </el-col>
       
          <el-col :span="12">
            <el-form-item label="培训项目" prop="trainItem">
              <el-input v-model="form.trainItem" placeholder="请输入" style="width:100%" :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习内容" prop="studyContent">
              <el-input v-model="form.studyContent" placeholder="请输入" style="width:100%" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训部门" prop="trainDept">
              <el-tree-select style="width:100%" class="inputDeep" v-model="form.trainDept" :data="deptOptions" @node-click="handleNodeClick($event,'form')" :disabled="isView"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择培训部门" check-strictly clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训时间" prop="trainDate">
              <el-date-picker style="width:100%" clearable v-model="form.trainDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择培训时间" :disabled="isView">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训对象" prop="trainOb">
              <el-input v-model="form.trainOb" placeholder="请输入" style="width:100%"  :disabled="isView"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授课人" prop="teacher">
              <el-input v-model="form.teacher" placeholder="请输入" style="width:100%" :disabled="isView" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="培训方式" prop="trainMethod">
              <el-input v-model="form.trainMethod" placeholder="请输入" style="width:100%" :disabled="isView" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="考核形式" prop="checkMethod">
              <el-input v-model="form.checkMethod" placeholder="请输入" style="width:100%" :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="相关文件" prop="fileList" >
          <div class="img-box">
            <CusUpload :modelValue="form.fileList1" @update:modelValue="updateValue($event,0)" :limit="1"  :disabled="isEdit"  :isShowTip="false" name="全年计划" />
            <div class="img-tips">全年计划</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList2" @update:modelValue="updateValue($event,1)" :disabled="isEdit" :isShowTip="false" name="方案通知" />
            <div class="img-tips">方案通知</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList3" @update:modelValue="updateValue($event,2)" :disabled="isEdit" :isShowTip="false" name="资料" />
            <div class="img-tips">资料</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList4" @update:modelValue="updateValue($event,3)" :disabled="isEdit" :isShowTip="false" name="签到表" />
            <div class="img-tips">签到表</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList5" @update:modelValue="updateValue($event,4)" :disabled="isEdit" :isShowTip="false" name="培训记录" />
            <div class="img-tips">培训记录</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList6" @update:modelValue="updateValue($event,5)" :disabled="isEdit" :isShowTip="false" name="评价报告" />
            <div class="img-tips">评价报告</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList7" @update:modelValue="updateValue($event,6)" :disabled="isEdit"  :isShowTip="false" name="试卷" />
            <div class="img-tips">试卷</div>
          </div>
          <div class="img-box">
            <CusUpload :modelValue="form.fileList8" @update:modelValue="updateValue($event,7)" :disabled="isEdit" :isShowTip="false" name="成绩表" />
            <div class="img-tips">成绩表</div>
          </div>

        </el-form-item>
        <el-form-item label="现场照片" prop="trainImg" v-if="isEdit">
          <ImageUpload :modelValue="form.trainImg" v-model="form.trainImg" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input style="width:100%" v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="isView" :rows="5"  />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" >
          <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
          <el-button @click="cancel" v-if="!isView">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Activity">
import { deptTreeSelect } from "@/api/system/user";
import { listTrain, getTrain, delTrain, addTrain, updateTrain } from "@/api/charge/train";
import CusUpload from "@/components/Custom/CusUpload"
import useUserStore from '@/store/modules/user'


const { proxy } = getCurrentInstance();
const { activity_type, activity_mode } = proxy.useDict('activity_type', 'activity_mode');

const userStore = useUserStore()
const activityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([])
const isEdit = ref(true)
const deptId = ref()
const isView=ref(false)

const data = reactive({
  form: {
    fileList: [],
    fileList1: [],
    fileList2: [],
    fileList3: [],
    fileList4: [],
    fileList5: [],
    fileList6: [],
    fileList7: [],
    fileList8: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // activityTime:'2024',
    // activityName: null,
    // activityDeptId: null,
    // status: null
  },
  rules: {
    deptId: [
      { required: true, message: '收费站不能为空', trigger: 'blur' },
    ],
    planDate: [
      { required: true, message: '计划时间不能为空', trigger: 'blur' },
    ],
    trainItem: [
      { required: true, message: '培训项目不能为空', trigger: 'blur' },
    ],
    studyContent: [
      { required: true, message: '学习内容不能为空', trigger: 'blur' },
    ],
    trainDept: [
      { required: true, message: '培训部门不能为空', trigger: 'blur' },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
/** 查询培训列表 */
function getList() {
  loading.value = true;
  listTrain(queryParams.value).then(response => {
    activityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    fileList: [],
    fileList1: [],
    fileList2: [],
    fileList3: [],
    fileList4: [],
    fileList5: [],
    fileList6: [],
    fileList7: [],
    fileList8: [],
  };
  proxy.resetForm("activityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.deptId = deptId.value;
  isEdit.value = false;
  isView.value=false;
  open.value = true;
  title.value = "添加培训";
}

/** 修改按钮操作 */
function handleUpdate(row,type) {

  reset();
  if(type==1){
    isEdit.value = false;
  }else{
    isEdit.value = true;
  }


  const _id = row.id || ids.value
  getTrain(_id).then(response => {
    form.value = response.data;
    form.value.deptId = deptId.value;
    
    if (response.data && response.data.tbActivityFile2List && response.data.tbActivityFile2List.length) {
      form.value.fileList=response.data.tbActivityFile2List;
      response.data.tbActivityFile2List.forEach(item => {
        switch (item.name) {
          //  <!-- 训：全年计划（1月15日前）、方案通知、资料、签到表、培训记录、照片、评价报告、试卷、成绩表） -->
          case '全年计划':
            form.value.fileList1 = [item]
            break;
          case '方案通知':
            form.value.fileList2 = [item]
            break;
          case '资料':
            form.value.fileList3 = [item]
            break;
          case '签到表':
            form.value.fileList4 = [item]
            break;
          case '培训记录':
            form.value.fileList5 = [item]
            break;
          case '评价报告':
            form.value.fileList6 = [item]
            break;
          case '试卷':
            form.value.fileList7 = [item]
            break;
          case '成绩表':
            form.value.fileList8 = [item]
            break;
        }

      })
    }else{
      form.value.fileList=[];
    }



    open.value = true;
    if(type==1){
      title.value = "查看详情";
      isView.value=true;
    }else{
      isView.value=false;
      title.value = "修改培训";
    }
   
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["activityRef"].validate(valid => {
    if (valid) {
      delete form.value.fileList1;
      delete form.value.fileList2;
      delete form.value.fileList3;
      delete form.value.fileList4;
      delete form.value.fileList5;
      delete form.value.fileList6;
      delete form.value.fileList7;
      delete form.value.fileList8;
      form.value.tbActivityFile2List=form.value.fileList;
      if (form.value.id != null) {
        updateTrain(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTrain(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function handleNodeClick(data, name) {
  if (name == 'queryParams') {
    queryParams.value.activityDeptId = data.id;
  } else {
    form.value.activityDeptId = data.id;
  }


}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除培训编号为"' + _ids + '"的数据项？').then(function () {
    return delTrain(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('audit/train/export', {
    ...queryParams.value
  }, `稽核培训计划_${new Date().getTime()}.xlsx`)
}

const updateValue = (data, index) => {
  let name = 'fileList' + (index + 1);
  if (data[0].url) {
    form.value[name] = data;
    form.value.fileList.push(data[0])
  } else {
    form.value[name] = [];
    let delIndex = -1;
    form.value.fileList.forEach((item, i) => {
      if (item.name == data[0].name) {
        delIndex = i
      }
    })
    form.value.fileList.splice(delIndex, 1)
  }



  // form.value.fileList[index] = data[0]
  // form.value.fileList[index].activityId = data[0].uid
  // form.value.fileList[index].id = data[0].uid
}

const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId;
      // userId.value = res.user.userId;
      // userName.value = res.user.userName;
      getList()
    }

  })
}

getDeptId()
getDeptTree()
</script>

<style scoped>
.img-box {
  margin-right: 15px;
}
.img-box .img-tips {
  font-size: 12px;
  line-height: 20px;
  text-align: center;
  margin-top: 10px;
}
.inputDeep >>> .el-input__inner {
  min-height: 38px;
}

</style>
